package com.hzhc.service.impl;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.common.FileExcelUtil;
import com.hzhc.dto.MemberVo;
import com.hzhc.dto.UserDto;
import com.hzhc.entity.*;
import com.hzhc.enumBean.LoginUserType;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.mapper.*;
import com.hzhc.service.SysUserSecurityService;
import com.hzhc.service.SysWxRoleService;
import com.hzhc.service.UserMemberService;
import com.hzhc.utils.*;
import com.hzhc.vo.SsoUserVo;
import com.hzhc.vo.UserMemberVo;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 用户会员表 服务实现类
 * </p>
 *
 * @author 功不唐捐
 * @since 2023-11-08
 */
@Service
@RequiredArgsConstructor
public class UserMemberServiceImpl extends ServiceImpl<UserMemberMapper, UserMember> implements UserMemberService {

    private final UserMemberMapper memberMapper;

    private final SysUserSecurityService securityService;

    private final SysWxRoleService wxRoleService;
    private final CompanyInfoMapper companyInfoMapper;
    private final SysDictMapper sysDictMapper;
    private final SysYzsRoleMenuMapper sysYzsRoleMenuMapper;
    private final SysYzsMenuMapper sysYzsMenuMapper;

    @Override
    public List<UserMemberVo> getUserMemberList(Page<UserMemberVo> page, UserMemberVo vo) {
        IPage<UserMemberVo> userMemberList = baseMapper.getUserMemberList(page, vo);
        return userMemberList.getRecords();
    }

    @Override
    public boolean updateUserMember(UserMemberVo vo) {
        UserMember userMember=new UserMember();
        BeanUtils.copyProperties(vo, userMember);
        return updateById(userMember);
    }

    @Override
    public boolean userMemberDelete(UserMemberVo vo) {
        UserMember userMember = getById(vo.getId());
        userMember.setDisable(true);
        return updateById(userMember);
    }

    @Override
    public boolean checkUserMemberByField(String field, String fieldstr, Integer id) {
        QueryWrapper<UserMember> queryWrapper = new QueryWrapper<UserMember>();
        queryWrapper.eq(field, fieldstr);
        if (id != null) {
            queryWrapper.ne("id", id);
        }

        queryWrapper.eq("disable",false);
        List<UserMember> list = baseMapper.selectList(queryWrapper);
        return !list.isEmpty();// 返回true 已经存在
    }
    @Override
    public boolean checkUserYZSMemberByField(String field, String fieldstr, Integer id,String fleetId) {
        QueryWrapper<UserMember> queryWrapper = new QueryWrapper<UserMember>();
        queryWrapper.eq(field, fieldstr);
        if (id != null) {
            queryWrapper.ne("id", id);
        }
        // 添加 fleetId 条件
        if (fleetId != null) {
            queryWrapper.eq("fleet", fleetId);
        }
        queryWrapper.eq("disable",false);
        List<UserMember> list = baseMapper.selectList(queryWrapper);
        return !list.isEmpty();// 返回true 已经存在
    }
    @Override
    public boolean checkDriverByField(String field, String fieldstr, Integer id,String companyName) {
        QueryWrapper<UserMember> queryWrapper = new QueryWrapper<UserMember>();
        queryWrapper.eq(field, fieldstr);
        if (id != null) {
            queryWrapper.ne("id", id);
        }
        // 添加公司名称条件
        if (companyName != null && !companyName.isEmpty()) {
            queryWrapper.eq("company_name", companyName);
        }
        queryWrapper.eq("disable",false);
        List<UserMember> list = baseMapper.selectList(queryWrapper);
        return !list.isEmpty();// 返回true 已经存在
    }
    @Override
    public boolean saveUserMember(UserMemberVo vo) {
        UserMember userMember=new UserMember();
        BeanUtils.copyProperties(vo, userMember);


        return save(userMember);
    }

    @Override
    public boolean resetPasswd(UserMember userMember) {

        return updateById(userMember);
    }

    @Override
    public ResultUtil<T> updatePwd(UserMember userMember) {
        UserMember userMember1 = baseMapper.selectById(userMember);
        if(!userMember1.getPassword().equals(userMember.getPasswordOld())){
            return ResultUtil.build(ResultUtilCodeEnum.OLD_PASSWORD_ERROR);
        }
        boolean b = updateById(userMember);
        return b ? ResultUtil.ok():ResultUtil.fail();
    }

    @Override
    public UserMember getByDriverName(String driverName,String companyId) {
        return baseMapper.getByDriverName(driverName,companyId);
    }

    @Override
    public boolean unlockRet(UserMember userMember) {
        boolean b = false;
        UserMember userMember1 = baseMapper.selectById(userMember.getId());
        userMember1.setLoginNum(0);
        userMember1.setLoginTime(null);
        b = updateById(userMember1);
        return b;
    }

    @Override
    public UserMember getUserMember(String loginname, String password,Integer flag) {
        QueryWrapper<UserMember> userMemberQueryWrapper = new QueryWrapper<>();
        userMemberQueryWrapper.and(wrapper -> wrapper.eq("username", loginname).or().eq("telephone", loginname))
                .eq("password", password);
        if(flag!=null){
            userMemberQueryWrapper.eq("user_type",flag);
        }
        UserMember userMember = baseMapper.selectOne(userMemberQueryWrapper);
        if(userMember!=null){
            if(userMember.getCompanyId()!=null){
                CompanyInfo companyInfo = companyInfoMapper.selectById(userMember.getCompanyId());
                if(companyInfo!=null){
                    userMember.setIsWhite(companyInfo.getIsWhite());
                    userMember.setNameSimple(companyInfo.getNameSimple());
                }
            }
        }
        return userMember;
    }

    @Override
    public ResultUtil<T> changePasswordRet(UserMemberVo vo) {
        //yzs用户 修改密码 java校验
        ResultUtil<T> rel = securityService.checkPasswordLevel(vo.getPassword());
        if (rel.getCode()==400){
            return rel;
        }

        UserMember userMember = memberMapper.selectById(vo.getId());
        if (vo.getOldpassword().trim().equals(userMember.getPassword().trim())){//输入的旧密码 和 数据库的密码一致
            //将新密码 更新到数据库
            userMember.setPassword(vo.getPassword());
            int i = memberMapper.updateById(userMember);
            return i>0?ResultUtil.ok():ResultUtil.fail();
        }else{
            return ResultUtil.build(ResultUtilCodeEnum.OLD_PASSWORD_ERROR);
        }
    }

    @Override
    public List<SysWxMenu> getSyswxMenuTree(Long memberId, String sysType, String title) {
        List<SysWxMenu> list = baseMapper.selectSyswxMenuTree(memberId,title);
        List<SysWxMenu> treelist = new ArrayList<>();
        for (SysWxMenu sysWxMenu : list) {
            if (sysWxMenu.getPid() == null || sysWxMenu.getPid() == 0L) {
                doChildren(list, sysWxMenu);
                treelist.add(sysWxMenu);
            }
        }
        return treelist;
    }

    @Override
    public List<UserMemberVo> getCompanyUserList(UserMemberVo vo) {
        return baseMapper.getCompanyUserList(vo);
    }

    @Override
    public List<UserMember> getDriverList() {
        return baseMapper.getDriverList();
    }

    @Override
    public ResultUtil<T> checkIsBlack(UserMemberVo vo) {
        UserMember member = getById(vo.getId());
        if (member.getIsBlack()==1){
            return ResultUtil.build(400,"该司机是黑名单！");
        }
        return ResultUtil.ok();
    }

    @Override
    public List<UserMemberVo> getYzsDriverList(UserMemberVo vo) {
        return baseMapper.getYzsDriverList(vo);
    }

    @Override
    public List<UserMemberVo> getDriverPageList(Page<UserMemberVo> page, UserMemberVo vo) {
        IPage<UserMemberVo> iPage = baseMapper.getDriverPageList(page,vo);
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<T> deleteDriver(UserMemberVo vo) {
        UserMember member = getById(vo.getId());
        String fleet = member.getFleet();
        String[] split = fleet.split(",");
        List<String> list = Arrays.asList(split);

        List<String> collect = list.stream().filter(item -> !item.equals(vo.getCompanyId().toString())).collect(Collectors.toList());
        String join = StringUtils.join(collect, ",");
        member.setFleet(join);
        boolean b = updateById(member);
        if (b){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public void updateDriver(UserMemberVo vo) {
        LambdaQueryWrapper<UserMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMember::getUsername,vo.getTelephone())
                        .eq(UserMember::getDisable,0);
        UserMember one = getOne(wrapper);

        // 扫码默认给司机角色
        SysWxRole sysWxRole = wxRoleService.getOne(new LambdaQueryWrapper<SysWxRole>().eq(SysWxRole::getName, "司机"));
        if (sysWxRole != null) {
            one.setSysWxRoleId(sysWxRole.getId());
        }

        String[] split = one.getFleet().split(",");
        List<String> list = new ArrayList<String>();
        list.addAll(Arrays.asList(split));
        if (list.contains(vo.getFleet().toString())){
        }else{
            list.add(vo.getFleet().toString());
        }
        String join = StringUtils.join(list, ",");
        one.setFleet(vo.getFleet());//新车队id字符串
        one.setPassword(vo.getPassword());//更新密码
        one.setGender(vo.getGender());//更新性别
        one.setRealName(vo.getRealName());//更新姓名
        boolean b = updateById(one);
    }

    @Override
    public ResultUtil<T> importDriverList(HttpServletRequest request, List<UserMember> drivers) {
        UserDto userDto = TokenUtil.getUser(request);
        LambdaQueryWrapper<CompanyInfo> companyInfoLambdaQueryWrapper=new LambdaQueryWrapper<CompanyInfo>();
        companyInfoLambdaQueryWrapper.select(CompanyInfo::getId,CompanyInfo::getName);
        List<CompanyInfo> result = companyInfoMapper.selectList(companyInfoLambdaQueryWrapper);
        HashMap<String,Long> nameToMap = new HashMap<>();
        for (CompanyInfo companyInfo :result){
            nameToMap.put(companyInfo.getName(),companyInfo.getId());
        }
        for (UserMember u : drivers) {
            SysWxRole sysWxRole = wxRoleService.getOne(new LambdaQueryWrapper<SysWxRole>().eq(SysWxRole::getName, "司机"));
            if (sysWxRole != null) {
                u.setSysWxRoleId(sysWxRole.getId());
            }
            String s = null;
            try {
                s = Sha1Util.sha1("Tsly@001");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            u.setPassword(s);
            u.setUsername(u.getTelephone());
            // 根据companyName匹配CompanyInfo中的id
            Long hdId = nameToMap.get(u.getCompanyName());
            if (hdId != null) {
                u.setUserType("2");
                u.setInoutflag(0);
                u.setFleet(Long.toString(hdId));
                u.setCompanyId(hdId);
            } else {
                return ResultUtil.build(ResultUtilCodeEnum.DEFAULT_HDID);
            }
        }
        boolean b = saveBatch(drivers);
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> importYZSDriverList(HttpServletRequest request, List<UserMember> drivers) {
        UserDto userDto = TokenUtil.getUser(request);
        LambdaQueryWrapper<CompanyInfo> companyInfoLambdaQueryWrapper=new LambdaQueryWrapper<CompanyInfo>();
        companyInfoLambdaQueryWrapper.select(CompanyInfo::getId,CompanyInfo::getName);
        List<CompanyInfo> result = companyInfoMapper.selectList(companyInfoLambdaQueryWrapper);
        HashMap<String,Long> nameToMap = new HashMap<>();
        for (CompanyInfo companyInfo :result){
            nameToMap.put(companyInfo.getName(),companyInfo.getId());
        }
        for (UserMember u : drivers) {
            SysWxRole sysWxRole = wxRoleService.getOne(new LambdaQueryWrapper<SysWxRole>().eq(SysWxRole::getName, "司机"));
            if (sysWxRole != null) {
                u.setSysWxRoleId(sysWxRole.getId());
            }
            String s = null;
            try {
                s = Sha1Util.sha1("Tsly@001");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            u.setPassword(s);
            u.setUsername(u.getTelephone());
            // 根据companyName匹配CompanyInfo中的id
            Long hdId = nameToMap.get(userDto.getCompanyName());
            if (hdId != null) {
                    u.setUserType("2");
                    u.setInoutflag(0);
                    u.setFleet(Long.toString(hdId));
                    u.setCompanyId(hdId);

            } else {
                return ResultUtil.build(ResultUtilCodeEnum.DEFAULT_HDID);
            }
        }
        boolean b = saveBatch(drivers);
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public void exportDriverFile(HttpServletRequest request, HttpServletResponse response, String exportExcelPathCms) {
        Map<String, Object> map = new HashMap<>();
        TemplateExportParams params = new TemplateExportParams(exportExcelPathCms);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        FileExcelUtil.downloadExcelIo(workbook, request, response, "司机导入");
    }

    @Override
    public ResultUtil<List<UserMemberVo>> DriverUpload(UserDto user, MultipartFile file) {
        List<UserMemberVo> list = new ArrayList<UserMemberVo>();
        List<String> driverList = new ArrayList<String>();
        ResultUtil<List<UserMemberVo>> build = new ResultUtil<>();
        if (file != null) {
            try {
                List<UserMemberVo> driverVos = EasypoiExcelUtils.importExcel(file, 0, 1, UserMemberVo.class);
                QueryWrapper<CarInfo> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("disable",0);
                List<UserMember> driverInfos = baseMapper.selectDrivers();
                for (UserMemberVo c:driverVos) { //校验数据
                    //校验账号
                    if (ObjectUtil.isEmpty(c)|| StrUtil.isBlank(c.getTelephone())){
                        c.setErrorInfo("文件中有空数据;");
                        break;
                    }
                    //司机不能再同一个公司重复
                    String errorInfo = checkDriver(driverList, driverInfos, c.getTelephone(),c.getUsername(),c.getCompanyName());
                    if (!StrUtil.isNotBlank(c.getCompanyName())){
                        errorInfo += "车队信息未填";
                    }
                    if (!StrUtil.isNotBlank(c.getRealName())){
                        errorInfo += "姓名信息未填";
                    }
                    if (!StrUtil.isNotBlank(c.getTelephone())){
                        errorInfo += "手机信息未填";
                    }
                    if (c.getGender()==null){
                        errorInfo += "性别信息未填";
                    }
                    c.setErrorInfo(errorInfo);
                    // 填充 driverList 属性
                    List<UserMember> matchedCarInfos = driverInfos.stream()
                            .filter(userMember -> userMember.getUsername().equals(c.getUsername()))
                            .collect(Collectors.toList());

                    c.setDrivers(matchedCarInfos);
                    list.add(c);
                }
                build = ResultUtil.build(list, ResultUtilCodeEnum.SUCCESS);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return build;
    }

    @Override
    public ResultUtil<List<UserMemberVo>> yzsDriverUpload(UserDto user, MultipartFile file) {
        List<UserMemberVo> list = new ArrayList<UserMemberVo>();
        List<String> driverList = new ArrayList<String>();
        ResultUtil<List<UserMemberVo>> build = new ResultUtil<>();
        if (file != null) {
            try {
                List<UserMemberVo> driverVos = EasypoiExcelUtils.importExcel(file, 0, 1, UserMemberVo.class);
                QueryWrapper<CarInfo> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("disable",0);
                List<UserMember> driverInfos = baseMapper.selectDrivers();
                for (UserMemberVo c:driverVos) { //校验数据
                    //校验账号
                    if (ObjectUtil.isEmpty(c)|| StrUtil.isBlank(c.getTelephone())){
                        c.setErrorInfo("文件中有空数据;");
                        break;
                    }
                    //司机不能再同一个公司重复
                    String errorInfo = checkYZSDriver(driverList, driverInfos,c.getTelephone(), c.getUsername(),c.getCompanyName());

                    if (!StrUtil.isNotBlank(c.getRealName())){
                        errorInfo += "姓名信息未填";
                    }
                    if (!StrUtil.isNotBlank(c.getTelephone())){
                        errorInfo += "手机信息未填";
                    }
                    c.setErrorInfo(errorInfo);
                    // 填充 driverList 属性
                    List<UserMember> matchedCarInfos = driverInfos.stream()
                            .filter(userMember -> userMember.getUsername().equals(c.getUsername()))
                            .collect(Collectors.toList());

                    c.setDrivers(matchedCarInfos);
                    list.add(c);
                }
                build = ResultUtil.build(list, ResultUtilCodeEnum.SUCCESS);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return build;
    }

    @Override
    public List<UserMember> getDriver(String telephone) {
        List<UserMember> userMembers = baseMapper.selectList(new QueryWrapper<UserMember>()
        .eq("disable" ,0)
        .eq("telephone",telephone)
        );
//        List<UserMember> userMembers = baseMapper.selectDriverList(telephone);
        return userMembers;
    }

    private String checkDriver(List<String> driverList, List<UserMember> driverInfoVos, String telephone,String userName,String companyName) {


        if (driverList.contains(userName)) {
            return "账号重复;";
        }

        if (driverList.contains(telephone)) {
            return "手机号重复;";
        }

        // 检查账号是否已经存在于 driverInfoVos 列表中，两个条件手机号码和公司名称同时存在不能成立
        boolean isExisting = driverInfoVos.stream().anyMatch(item ->
                telephone.equals(item.getTelephone()) && companyName.equals(item.getCompanyName())
        );
        if (isExisting) {
            return "该司机在同一公司下已存在;";
        }
        // 添加到 carList 中，标记shouji号为唯一
        driverList.add(telephone);
        return "";
    }

    private String checkYZSDriver(List<String> driverList, List<UserMember> driverInfoVos, String telephone,String userName,String companyName) {
//        if (userName == null || userName.trim().isEmpty()) {
//            return "账号号不能为空;";
//        }
        // 检查车牌号是否已经存在于列表中
        if (driverInfoVos.contains(userName)) {
            return "账号重复;";
        }

        // 检查账号是否已经存在于 carInfoVos 列表中，两个条件车牌和公司同时存在不能成立

        boolean isExisting = driverInfoVos.stream().anyMatch(item ->
                telephone.equals(item.getTelephone())
        );
        if (isExisting) {
            return "该司机在同一公司下已存在;";
        }
        // 添加到 carList 中，标记车牌号为唯一
        driverList.add(userName);
        return "";
    }


    private void doChildren(List<SysWxMenu> list, SysWxMenu pmenu) {
        List<SysWxMenu> childList = new ArrayList<>();
        for (SysWxMenu sysWxMenu : list) {
            if (pmenu.getId().equals(sysWxMenu.getPid())) {
                doChildren(list, sysWxMenu);
                childList.add(sysWxMenu);
            }
        }
        if (childList.size() > 0) {
            pmenu.setChildren(childList);
        }
    }

    @Override
    public MemberVo syncUsersAutoLogin(HttpServletRequest request, SsoUserVo ssoUserVo, Long roleId) {
        UserMember userMember = null;
        if (ssoUserVo.getDwfwOldid() == null) {
            //增量用户
            //查看oneid在我们系统存不存在该用户
            userMember = baseMapper.selectOne(new LambdaQueryWrapper<UserMember>()
                    .eq(UserMember::getOneId, ssoUserVo.getId()));
            if (userMember == null) {
                userMember = baseMapper.selectOne(new LambdaQueryWrapper<UserMember>().eq(UserMember::getUsername, ssoUserVo.getUsername()));
                if (userMember == null) {
                    userMember = saveSysUser(ssoUserVo, roleId);
                } else {
                    userMember.setOneId(ssoUserVo.getId());
                    userMember.setCompanyId(ssoUserVo.getCompanyId());
                    updateById(userMember);
                }
            }else{
                userMember = baseMapper.selectOne(new LambdaQueryWrapper<UserMember>().eq(UserMember::getUsername, ssoUserVo.getUsername()));
                if (userMember != null) {
                    userMember.setOneId(ssoUserVo.getId());
                    userMember.setCompanyId(ssoUserVo.getCompanyId());
                    updateById(userMember);
                }
            }
        } else {
            userMember = baseMapper.selectOne(new LambdaQueryWrapper<UserMember>().eq(UserMember::getId, ssoUserVo.getCzOldid()));
            if (userMember == null) {
                userMember = baseMapper.selectOne(new LambdaQueryWrapper<UserMember>().eq(UserMember::getUsername, ssoUserVo.getUsername()));
                if (userMember == null) {
                    userMember = saveSysUser(ssoUserVo, roleId);
                }
            }
        }
        //自动登录
        MemberVo memberVo = autoLogin(userMember, ssoUserVo, request);
        return memberVo;
    }

    private UserMember saveSysUser(SsoUserVo ssoUserVo, Long roleId) {
        UserMember member = new UserMember();
        member.setUsername(ssoUserVo.getUsername());
        member.setRealName(ssoUserVo.getName());
        member.setTelephone(ssoUserVo.getPhone());
        member.setCompanyId(ssoUserVo.getCompanyId());
        member.setPassword("44222fa5906ed63355f033bfb39f1f5b582d66fa");
        member.setYzsRole(roleId.toString());
        member.setOneId(ssoUserVo.getId());
        member.setCreateTime(LocalDateTime.now());
        save(member);
        return member;
    }

    private MemberVo autoLogin(UserMember userMember, SsoUserVo ssoUserVo, HttpServletRequest request) {
        UserMember member = baseMapper.findUserById(userMember.getId());
        String uuid = UUIDUtils.getUUID() + member.getId();
        member.setSalt(uuid);
        // 更新一下用户表用户信息
        member.setLastLoginTime(LocalDateTime.now());
        member.setLastLoginIp(IpUtils.getIpAddr(request));
        member.setSalt(uuid);
        MemberVo memberVo=new MemberVo();
        boolean b = updateById(member);
        if (b) {
            List<UserMember> list = Collections.singletonList(member);
            MemberVo vo = getMemberVo(list);
            vo.setAppToken(ssoUserVo.getAppToken());
            vo.setAccessToken(ssoUserVo.getAccessToken());
            List<SysYzsMenu> sysMenus = new ArrayList<>();
            List<SysYzsRoleMenu> sysYzsRoleMenus = sysYzsRoleMenuMapper.selectList(Wrappers.<SysYzsRoleMenu>lambdaQuery().eq(SysYzsRoleMenu::getYzsRoleId, list.get(0).getYzsRole()));
            for (SysYzsRoleMenu sysYzsRoleMenu : sysYzsRoleMenus) {
                SysYzsMenu sysYzsMenu = sysYzsMenuMapper.selectById(sysYzsRoleMenu.getYzsMenuId());
                sysMenus.add(sysYzsMenu);
            }
            vo.setMenusList(sysMenus);
            SessionMemberUtil.setMember(request, vo);

            if(member != null) {
                //获取用户所有角色
                String token = TokenUtil.signMemberToken(member);
                BeanUtils.copyProperties(member,vo);
                vo.setToken(token);
                vo.setUserType(LoginUserType.MEMBER.getCode());
                //保存登录时间
                member.setLastLoginTime(LocalDateTime.now());
                updateById(member);
                BeanUtils.copyProperties(vo,memberVo);
            }
        }
        return memberVo;
    }

    private MemberVo getMemberVo(List<UserMember> list) {
        UserMember st = list.get(0);
        MemberVo vo = new MemberVo();
        vo.setId(st.getId().intValue());
        vo.setRealname(st.getRealName());
        vo.setSalt(st.getSalt());
        vo.setNickname(st.getNickname());
        vo.setTelephone(st.getTelephone());
        vo.setCompanyId(st.getCompanyId());
        vo.setCarNo(st.getCarNo());
        vo.setUsername(st.getUsername());
        CompanyInfo comInfo = companyInfoMapper.selectById(st.getCompanyId());
        if(comInfo != null){
            vo.setCompanyname(comInfo.getName());
            vo.setCompanytel(comInfo.getTelephone());
            if (comInfo.getCustomerGrade() != null) {
                SysDict sysDict = sysDictMapper.selectById(comInfo.getCustomerGrade());
                vo.setCustomerGradeName(sysDict.getName());
            } else {
                vo.setCustomerGradeName("普通用户");
            }
        }

        return vo;
    }
}
